package com.yonyou.crm.common.login.util;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yonyou.crm.common.exception.CrmBusinessException;
import com.yonyou.crm.common.login.context.LoginContextConstant;
import com.yonyou.crm.sys.user.service.UserBizServiceImpl;
import com.yonyou.iuap.context.InvocationInfoProxy;

@Component
public class LoginContextUtil {

	@Autowired
	private UserBizServiceImpl userService;
	
	/**
	 * 设置登录上下文信息
	 * 外部系统调用时使用，如自动任务
	 * @param tenantId 租户id
	 * @param userId 用户id
	 * @param roleId 角色id
	 */
	public void setLoginContext(String tenantId, String userId, String roleId) {
				
		if (StringUtils.isBlank(tenantId) 
				|| StringUtils.isBlank(userId) 
				|| StringUtils.isBlank(roleId)) {
			throw new CrmBusinessException("参数中不能包含空值。");
		}

		if (userService == null) {
			throw new CrmBusinessException("请使用@Autowired注入方式调用此工具类。");
		}
		
		Map<String, Object> userMap = userService.getLoginContext(new Long(userId));
		
		if (userMap == null || userMap.size() == 0) {
			throw new CrmBusinessException("获取用户信息失败。");
		}
		
		String orgId = (String) userMap.get(LoginContextConstant.OrgId);
		if (orgId != null) {
			InvocationInfoProxy.setParameter(LoginContextConstant.OrgId, orgId);
		}
		
		String deptId = (String) userMap.get(LoginContextConstant.DeptId);
		if (deptId != null) {
			InvocationInfoProxy.setParameter(LoginContextConstant.DeptId, deptId);
		}

		InvocationInfoProxy.setParameter(LoginContextConstant.UserId, userId);
		InvocationInfoProxy.setParameter(LoginContextConstant.RoleId, roleId);
		InvocationInfoProxy.setTenantid(tenantId.toString());
	}

}
